package com.example.weight.householdWaste;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class CombustiblePutrescibleActivity extends AppCompatActivity {

    String name, factory;

    private EditText carNum, comeTime, leaveTime, transportWeight, restWeight, comment;

    private RadioGroup tranGroup, restGroup;
    private RadioButton tranComb, tranPutre, restComb, restPutre;
    private String tranType, restType;

    private boolean isTransWeight;

    private SharedPreferences preferences;

    private ItemAdapter adapter;
    private List<String> nameList;

    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_combustible_putrescible);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.combustible_putrescible_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                CombustiblePutrescibleActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        carNum = findViewById(R.id.combustible_putrescible_carNum);
        comeTime = findViewById(R.id.combustible_putrescible_come_time);
        leaveTime = findViewById(R.id.combustible_putrescible_leave_time);
        transportWeight = findViewById(R.id.combustion_putrescible_transport);
        tranGroup = findViewById(R.id.combustible_putrescible_tranGroup);
        tranComb = findViewById(R.id.combustible_putrescible_tranCom);
        tranPutre = findViewById(R.id.combustion_putrescible_tranPut);
        restWeight = findViewById(R.id.combustible_putrescible_rest);
        restGroup = findViewById(R.id.combustible_putrescible_restGroup);
        restComb = findViewById(R.id.combustible_putrescible_restCom);
        restPutre = findViewById(R.id.combustible_putrescible_restPut);
        comment = findViewById(R.id.combustible_putrescible_comment);

        tranGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton radioButton = findViewById(checkedId);
            tranType = radioButton.getText().toString();
        });
        restGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton radioButton = findViewById(checkedId);
            restType = radioButton.getText().toString();
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/storageBoxClean/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                carNum.setText(data.getString("wagonNumber"));
                                comeTime.setText(data.getString("arrivalTime"));
                                leaveTime.setText(data.getString("leaveTime"));}
//                                transportWeight.setText(data.getString("cleanWeight"));
//                                if (data.getString("cleanType").equals("可燃物"))
//                                    tranComb.setChecked(true);
//                                else
//                                    tranPutre.setChecked(true);
//                                restWeight.setText(data.getString("residueWeight"));
//                                if (data.getString("residueType").equals("可燃物"))
//                                    restComb.setChecked(true);
//                                else
//                                    restPutre.setChecked(true);
//                                comment.setText(data.getString("remarks"));
//                                Toast.makeText(CombustiblePutrescibleActivity.this,
//                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(CombustiblePutrescibleActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        // 设置输入记录缓存
        preferences = getSharedPreferences("combustible_putrescible", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("comment", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
        ListView listView = new ListView(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (adapter.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter.getList();
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = nameList.get(position);
            comment.setText(result);
            popupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        popupWindow = new PopupWindow(listView ,width, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置点击外部区域可以取消popupWindow
        popupWindow.setOutsideTouchable(true);

        comment.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                popupWindow.showAsDropDown(comment);
            }
        });

        comeTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                TimePickerDialog timePickerDialog = new TimePickerDialog(CombustiblePutrescibleActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                comeTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            comeTime.clearFocus();
                        }
                    }
                });
                timePickerDialog.show();
            }
        });
        leaveTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                TimePickerDialog timePickerDialog = new TimePickerDialog(CombustiblePutrescibleActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                leaveTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            leaveTime.clearFocus();
                        }
                    }
                });
                timePickerDialog.show();
            }
        });
    }

    public void selectComeTime(View view) {
        Calendar calendar = Calendar.getInstance();
        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        final int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                comeTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true)
                .show();
    }

    public void selectLeaveTime(View view) {
        Calendar calendar = Calendar.getInstance();
        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        final int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                leaveTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        String weight = data.getStringExtra("weight");
        if (isTransWeight)
            transportWeight.setText(weight);
        else
            restWeight.setText(weight);
    }

    public void goWeightForTransport(View view) {
        isTransWeight = true;
        Intent intent = new Intent(CombustiblePutrescibleActivity.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void goWeightForRest(View view) {
        isTransWeight = false;
        Intent intent = new Intent(CombustiblePutrescibleActivity.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void save(View view) {
        if (carNum.getText().toString().equals("")) {
            Toast.makeText(this, "请填写车号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (comeTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写来厂时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (leaveTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写离场时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(transportWeight.getText().toString())) {
            Toast.makeText(this, "清运物料请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!tranComb.isChecked() && !tranPutre.isChecked()) {
            Toast.makeText(this, "请选择清运物料类型", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(restWeight.getText().toString())) {
            Toast.makeText(this, "箱内剩料请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!restComb.isChecked() && !restPutre.isChecked()) {
            Toast.makeText(this, "请选择箱内剩料类型", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新nameList
                List<Item> tempItemList = adapter.getList();
                if (tempItemList.size() != nameList.size()) {
                    nameList.clear();
                    for (Item item : tempItemList) {
                        nameList.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String current = comment.getText().toString();
                if (!current.equals("") && !nameList.contains(current)) {
                    nameList.add(current);
                }

                editor.putStringSet("comment", new HashSet<>(nameList));
                editor.apply();

                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/storageBoxClean/add";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");

//                                    carNum.setText("");
//                                    comeTime.setText("");
//                                    leaveTime.setText("");
//                                    transportWeight.setText("");
//                                    restWeight.setText("");
//                                    comment.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(CombustiblePutrescibleActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(CombustiblePutrescibleActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(CombustiblePutrescibleActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("wagonNumber", carNum.getText().toString());
                        map.put("arrivalTime", comeTime.getText().toString());
                        map.put("leaveTime", leaveTime.getText().toString());
                        map.put("cleanWeightstr", transportWeight.getText().toString());
                        map.put("residueWeightstr", restWeight.getText().toString());
                        map.put("cleanType", tranType);
                        map.put("residueType", restType);
                        map.put("recordingPerson", name);
                        map.put("remarks", comment.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();

    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
